package cn.fl.collection.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.*;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.collection.condition.RskCltAuthRcvAplQC;
import cn.fl.collection.constant.CollectionConstant;
import cn.fl.collection.dto.RskCltAuthRcvAplDTO;
import cn.fl.collection.service.IRskCltAuthRebateService;
import cn.fl.collection.service.IRskCltAuthService;
import cn.fl.collection.vo.RskCltAuthVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.vo.SysUlFilesRecVO;
import cn.fl.upload.constant.UploadConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fl.flow.facade.flow.constant.FlowConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @Description:    委外催收回款管理Controller
* @Author:         liurong
* @CreateDate:     2020/4/22 15:12
* @Version:        1.0
*/
@Controller
@RequestMapping("/clt/auth/rebate")
public class RskCltAuthRebateController {

    @Autowired
    private IRskCltAuthService rskCltAuthService;

    @Autowired
    private IRskCltAuthRebateService rskCltAuthRebateService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    /**
     * 回款申请页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/showAddRebatePage.do", method = {RequestMethod.GET})
    public ModelAndView showAddRebatePage(HttpServletRequest request, HttpServletResponse response) {
        String cltAuthId = request.getParameter("cltAuthId");
        try {
            if (StringUtils.isEmpty(cltAuthId)) {
                throw new BaseException("请求参数：委外催收ID不能为空！");
            }
            RskCltAuthVO rskCltAuthVO = rskCltAuthService.selectById(Long.parseLong(cltAuthId));
            if (rskCltAuthVO == null) {
                throw new BaseException("委外催收数据不存在！");
            }
            rskCltAuthVO.setStartDateStr(DateUtils.formatDateToString(rskCltAuthVO.getStartDate(), DateUtils.YYYY_MM_DDHHMMSS));

            List<KeyValueVO> payWayCdList = this.sysDictionaryApiService.getKvList(CollectionConstant.CLT_REFUND_WAY, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());

            ModelAndView view = new ModelAndView("collection/rebate/addRebatePage");
            view.addObject("cltAuthId", cltAuthId);
            view.addObject("authVo", rskCltAuthVO);
            view.addObject("payWayCdList", JSON.toJSONString(payWayCdList));
            return view;
        } catch (Exception e) {
            BaseLogUtils.newLogger(cltAuthId + "显示新增回款申请页面失败！操作人：" + CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
    }

    /**
     * 提交回款申请
     * @param request
     * @param
     * @return
     */
    @RequestMapping(value = "/addRebateApply.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addRebateApply(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        String fileParams = request.getParameter("fileParams");
        String cltAuthId = request.getParameter("cltAuthId");
        String recoveryAmt = request.getParameter("recoveryAmt");
        String payDt = request.getParameter("payDt");
        String payWay = request.getParameter("payWay");
        String payer = request.getParameter("payer");
        try {
            if (StringUtils.isEmpty(cltAuthId)) {
                throw new BaseException("委外催收ID不能为空！");
            }
            if (StringUtils.isEmpty(recoveryAmt)) {
                throw new BaseException("打款金额不能为空！");
            }
            if (StringUtils.isEmpty(payDt)) {
                throw new BaseException("打款日期不能为空！");
            }
            if (StringUtils.isEmpty(payWay)) {
                throw new BaseException("来款方式不能为空！");
            }
            if (StringUtils.isEmpty(payer)) {
                throw new BaseException("打款人不能为空！");
            }
            if (StringUtils.isEmpty(fileParams)) {
                throw new BaseException("请上传附件！");
            }
            List<SysUlFilesRecVO> fileList = JSON.parseArray(fileParams, SysUlFilesRecVO.class);
            if (CollectionUtils.isEmpty(fileList)) {
                throw new BaseException(SysLogConstant.LOG_CMM_SYS_ERROR, "请上传附件！");
            }
            for (SysUlFilesRecVO sysUlFilesRecVO : fileList) {
                sysUlFilesRecVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
                sysUlFilesRecVO.setOrgCd(PrjBscInfoConstant.CODE_PRJ_FILE_DEF_ORG);
                sysUlFilesRecVO.setAbsLocPath(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH) + sysUlFilesRecVO.getFilePath());
            }
            RskCltAuthRcvAplDTO applyDto = new RskCltAuthRcvAplDTO();
            applyDto.setCltAuthId(Long.parseLong(cltAuthId));//委外催收表ID
            applyDto.setRecoveryAmt(DecimalUtils.convertYuanToFen(Double.parseDouble(recoveryAmt)));//回款金额
            applyDto.setPayWay(payWay);// 回款方式（RSK0029）1-APP还款  2-银行转账  3-其他
            applyDto.setPayDt(DateUtils.formatStringToDate(payDt, DateUtils.YYYY_MM_DD));// 回款时间
            applyDto.setPayer(payer);// 付款人，打款人
            applyDto.setAuthOrgCd(CurrentThreadContext.getCurrentOrgCd());// 催收机构
            applyDto.setAudStsCd(Long.parseLong(FlowConstant.FLOW_CHECK_STATE_IN));//状态(1-审核中 2-审核通过 3-审核不通过)
            applyDto.setCrtTm(new Date());
            applyDto.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            applyDto.setCrtUsrNm(CurrentThreadContext.getCurrentUserName());
            applyDto.setMdfTm(new Date());
            applyDto.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
            applyDto.setMdfUsrNm(CurrentThreadContext.getCurrentUserName());

            DataResultDTO dataResultDTO = rskCltAuthRebateService.addApplyAndStartFlow(applyDto, fileList);
            if (dataResultDTO == null || dataResultDTO.getSuccess() == BaseConstant.IS_YESNO_NO) {
                throw new BaseException("提交回款申请失败！");
            }
        } catch (BaseException e) {
            BaseLogUtils.newLogger("委外催收-->提交回款申请业务异常！" + CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_OPERATE_SUCC + "：" + e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.newLogger("委外催收-->提交回款申请系统异常！" + CurrentThreadContext.getCurrentUserName()).setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
        }
        return result;
    }

    /**
     * 到回款管理列表
     */
    @RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("collection/rebate/rskCltAuthAplList");
        RskCltAuthRcvAplQC condition = new RskCltAuthRcvAplQC();
        List<RskCltAuthRcvAplDTO> applyDTOS = rskCltAuthRebateService.selectRskCltAuthRcvAplList(condition);
        int totalApl = 0;
        Long totalRecoveryAmt = 0L;
        if(CollectionUtils.isNotEmpty(applyDTOS)){
            totalApl = applyDTOS.size();
            for(RskCltAuthRcvAplDTO d : applyDTOS){
                totalRecoveryAmt += d.getRecoveryAmt();
            }
        }
        //合计回款记录数
        view.addObject("totalApl",totalApl);
        //合计回款金额
        //view.addObject("totalRecoveryAmt",DecimalUtils.convertFenToYuan(totalRecoveryAmt));
        view.addObject("totalRecoveryAmt",totalRecoveryAmt);
        return view;
    }

    /**
     * 回款管理列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String paySchNo = request.getParameter("paySchNo");
        String cstNm = request.getParameter("cstNm");
        String cstMgrOrgCd = request.getParameter("cstMgrOrgCd");
        //回款申请开始日期
        String aplCrtTmStart = request.getParameter("aplCrtTmStart");
        //回款申请结束日期
        String aplCrtTmEnd = request.getParameter("aplCrtTmEnd");
        //融资租赁合同号
        String lsCntNo= request.getParameter("lsCntNo");
        //催收机构（委案机构）
        String authOrgCd= request.getParameter("authOrgCd");

        Pager page = new Pager();
        RskCltAuthRcvAplQC qc = new RskCltAuthRcvAplQC();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        if (StringUtils.isNotEmpty(paySchNo)) {
            qc.setPaySchNo(paySchNo);
        }
        if (StringUtils.isNotEmpty(cstNm)) {
            qc.setCstNm(cstNm);
        }
        if (StringUtils.isNotEmpty(cstMgrOrgCd)) {
            qc.setCstMgrOrgCd(cstMgrOrgCd);
        }
        if (StringUtils.isNotEmpty(aplCrtTmStart)) {
            qc.setAplCrtTmStart(DateUtils.formatStringToDate(aplCrtTmStart,DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotEmpty(aplCrtTmEnd)) {
            qc.setAplCrtTmEnd(DateUtils.formatStringToDate(aplCrtTmEnd,DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotEmpty(lsCntNo)) {
            qc.setLsCntNo(lsCntNo);
        }
        if (StringUtils.isNotEmpty(authOrgCd)) {
            qc.setAuthOrgCd(authOrgCd);
        }
        page.setCondition(qc);

        //TODO SOMETHING
        page = this.rskCltAuthRebateService.selectRskCltAuthRcvAplPage(page);
        List<RskCltAuthRcvAplDTO> list = (List<RskCltAuthRcvAplDTO>) page.getResultList();
        ListPageVO<RskCltAuthRcvAplDTO> listPage = new ListPageVO<RskCltAuthRcvAplDTO>(list, page.getTotalCount());
        return listPage;
    }
    /**
     * 合计回款记录数,合计回款金额
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getInitTotalApl.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object getInitTotalApl(HttpServletRequest request, HttpServletResponse response) {
        String paySchNo = request.getParameter("paySchNo");
        String cstNm = request.getParameter("cstNm");
        String cstMgrOrgCd = request.getParameter("cstMgrOrgCd");
        //回款申请开始日期
        String aplCrtTmStart = request.getParameter("aplCrtTmStart");
        //回款申请结束日期
        String aplCrtTmEnd = request.getParameter("aplCrtTmEnd");
        //融资租赁合同号
        String lsCntNo= request.getParameter("lsCntNo");
        //催收机构（委案机构）
        String authOrgCd= request.getParameter("authOrgCd");

        RskCltAuthRcvAplQC qc = new RskCltAuthRcvAplQC();
        if (StringUtils.isNotEmpty(paySchNo)) {
            qc.setPaySchNo(paySchNo);
        }
        if (StringUtils.isNotEmpty(cstNm)) {
            qc.setCstNm(cstNm);
        }
        if (StringUtils.isNotEmpty(cstMgrOrgCd)) {
            qc.setCstMgrOrgCd(cstMgrOrgCd);
        }
        if (StringUtils.isNotEmpty(aplCrtTmStart)) {
            qc.setAplCrtTmStart(DateUtils.formatStringToDate(aplCrtTmStart,DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotEmpty(aplCrtTmEnd)) {
            qc.setAplCrtTmEnd(DateUtils.formatStringToDate(aplCrtTmEnd,DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotEmpty(lsCntNo)) {
            qc.setLsCntNo(lsCntNo);
        }
        if (StringUtils.isNotEmpty(authOrgCd)) {
            qc.setAuthOrgCd(authOrgCd);
        }
        BaseLogUtils.newLogger("getInitTotalApl qc:" + JSONObject.toJSONString(qc), CurrentThreadContext.getCurrentUserName()).setKeys("getInitTotalApl").info();
        List<RskCltAuthRcvAplDTO> applyDTOS = rskCltAuthRebateService.selectRskCltAuthRcvAplList(qc);
        BaseLogUtils.newLogger("getInitTotalApl applyDTOS:" + JSONObject.toJSONString(applyDTOS), CurrentThreadContext.getCurrentUserName()).setKeys("getInitTotalApl").info();
        int totalApl = 0;
        Long totalRecoveryAmt = 0L;
        if(CollectionUtils.isNotEmpty(applyDTOS)){
            totalApl = applyDTOS.size();
            for(RskCltAuthRcvAplDTO d : applyDTOS){
                totalRecoveryAmt += d.getRecoveryAmt();
            }
        }
        Map<String,Object> aplMap = new HashMap<>();
        //合计回款记录数
        aplMap.put("totalApl",totalApl);
        //合计回款金额
        //request.setAttribute("totalRecoveryAmt",DecimalUtils.convertFenToYuan(totalRecoveryAmt));
        aplMap.put("totalRecoveryAmt",totalRecoveryAmt);
        return aplMap;
    }


}
